package com.streamkar.common.interceptor;

import com.streamkar.common.config.session.UserSession;
import com.streamkar.constant.Constants;
import com.streamkar.constant.ReturnCode;
import com.streamkar.entity.base.Response;
import com.streamkar.entity.domain.Account;
import com.streamkar.util.Responses;
import com.streamkar.util.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName SessionInterceptor
 * @Description
 * @Author tyfrost
 * @Date 2018/11/26 4:29 PM
 * @Version 1.0
 */
public class SessionInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(SessionInterceptor.class);

    private UserSession userSession = new UserSession();

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView arg)
            throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Response result = new Response();
        String requestURI = request.getRequestURI();
        if ("/check".equals(requestURI) || "/login".equals(requestURI) || "/incentive".equals(requestURI)) {
            return Boolean.TRUE;
        }
        Environment environment = (Environment)SpringContextUtil.getBean("environment");
        String dev = environment.getProperty("spring.profiles");

        // 拦截
        Account account = null;
        if ("dev".equals(dev)) {
            if (!userSession.checkMockSession(request)) {
                LOGGER.info("user session check, request url [{}],need login ", requestURI);
                result.setCode(ReturnCode.SESSION_TIMEOUT);
                Responses.response(response, result);
                return Boolean.FALSE;
            }
            account = userSession.getMockAccountSession(request);
        } else {
            if (!userSession.checkSession(request)) {
                LOGGER.info("user session check, request url [{}],need login ", requestURI);
                result.setCode(ReturnCode.SESSION_TIMEOUT);
                Responses.response(response, result);
                return Boolean.FALSE;
            }
            account = userSession.getAccountSession(request);
        }

        if (null == account) {
            LOGGER.info("user session check, request url [{}],session need login ", requestURI);
            result.setCode(ReturnCode.SESSION_TIMEOUT);
            Responses.response(response, result);
            return Boolean.FALSE;
        }
        // 获取Account信息，对prefix进行匹配 /agency/匹配代理agency role,/admin/匹配admin role /telent/匹配 talent
        if (requestURI.startsWith(Constants.ADMIN_PREFIX)) {
            if (!Constants.TALENT_MANAGER.equals(account.getRole())) {
                LOGGER.info("user session check, request url [{}], not match user role {} ", requestURI, account.getRole());
                result.setCode(ReturnCode.DENY_ACCESS);
                Responses.response(response, result);
                return Boolean.FALSE;
            }
        } else if (requestURI.startsWith(Constants.AGENCY_PREFIX)) {
            if (!Constants.AGENCY.equals(account.getRole())) {
                LOGGER.info("user session check, request url [{}], not match user role {} ", requestURI, account.getRole());
                result.setCode(ReturnCode.DENY_ACCESS);
                Responses.response(response, result);
                return Boolean.FALSE;
            }
        } else if (requestURI.startsWith(Constants.TALENT_PREFIX)) {
            if (!Constants.TALENT.equals(account.getRole())) {
                LOGGER.info("user session check, request url [{}], not match user role {} ", requestURI, account.getRole());
                result.setCode(ReturnCode.DENY_ACCESS);
                Responses.response(response, result);
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }
}
